package sk.hackcraft.multibox.server.net.servlet;

import org.json.JSONArray;
import org.json.JSONObject;

import sk.hackcraft.multibox.server.Playlist;
import sk.hackcraft.multibox.server.Song;
import sk.hackcraft.multibox.server.User;
import sk.hackcraft.multibox.server.net.Server;
import sk.hackcraft.multibox.server.net.UserServlet;
import sk.nixone.http.ServletExchange;

public class PlaylistServlet extends UserServlet {
	public PlaylistServlet(Server server) {
		super(server);
	}

	@Override
	public JSONObject doUserRequest(User user, Method method,
			ServletExchange exchange, JSONObject response) {

		String songString = exchange.getQueryValue("song");
	
		if(songString != null) {
			Song song = Song.all.get((long)Long.valueOf(songString));
			if(song == null)
				throw new NullPointerException();
			
			server.box.playlist.addSongToPlay(song);
		}
		
		JSONArray list = new JSONArray();
		
		Playlist.SongRecord playing = server.box.playlist.getPlaying();
		Playlist.SongRecord cursor = playing;
		do {
			list.put(cursor.song.toJSON());
			cursor = cursor.next;
		} while(playing != cursor);
		
		response.put("songs", list);
		
		return response;
	}
}
